package org.test.mail;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.scirp.ijmis.action.base.BaseAction;
import org.scirp.ijmis.po.personpaper.SendEmailLog;
import org.scirp.ijmis.service.personpaper.ISendEmailLogService;
import org.scirp.ijmis.service.personpaper.impl.SendEmailLogServiceImpl;

public class SendMail extends BaseAction {
	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(SendMail.class);

	/**
	 * 读邮件模板 author 李建 date 2010-05-14
	 */
	public String readFile(String sourceFile) throws Exception {
		File file = new File(sourceFile);

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			StringBuilder sb = new StringBuilder();

			String line = reader.readLine();
			while (line != null) {
				sb.append(line);
				line = reader.readLine();
			}
			reader.close();
			return sb.toString();
		} catch (Exception e) {
			return null;
		} 
	}

	/**
	 * 发送邮件 author 李建 date 2010-05-14
	 */
	public boolean sendMail(String smtp, String sendFrom, String sendTo, String smtpName, String smtpPassword, String content, String subject) throws Exception {
		final String _smtpName = smtpName;
		final String _smtpPassword = smtpPassword;

		Properties props = new Properties();
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", smtp);
		Session session = Session.getInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(_smtpName, _smtpPassword);
			}
		});
		session.setDebug(false);

		MimeMessage msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(MimeUtility.encodeText(sendFrom)));
		msg.setRecipients(RecipientType.TO, InternetAddress.parse(sendTo));
		msg.setSubject(subject);

		MimeMultipart msgMultipart = new MimeMultipart("mixed");
		msg.setContent(msgMultipart);
		MimeBodyPart contents = new MimeBodyPart();
		msgMultipart.addBodyPart(contents);

		MimeMultipart bodyMultipart = new MimeMultipart("related");
		contents.setContent(bodyMultipart);
		MimeBodyPart htmlPart = new MimeBodyPart();
		bodyMultipart.addBodyPart(htmlPart);

		htmlPart.setContent(content, "text/html;charset=gbk");

		msg.setHeader("Date", new Date().toString());

		// 设置发送时间
		msg.setSentDate(new Date());
		msg.saveChanges();

		// OutputStream ips = new FileOutputStream("d:/demo3.eml");
		// msg.writeTo(ips);
		// ips.close();

		// msg = new MimeMessage(session, new FileInputStream("d:/demo3.eml"));

		// msg = new MimeMessage(session);

		session.setDebug(false);

		try {
			Transport.send(msg, InternetAddress.parse(sendTo));
			return true;
		} catch (Exception e) {
			log.error("mail sender error To: " + sendTo + " Mail Title: " + subject , e);  
			return false;
		}
	}

	/**
	 * 发送邮件 author 李建 date 2010-05-14
	 */
	public boolean sendMail(String smtp, String sendFrom, String sendTo, String smtpName, String smtpPassword, String content, String subject, String accessoryAddress, String accessoryName) throws Exception {
		final String _smtpName = smtpName;
		final String _smtpPassword = smtpPassword;

		Properties props = new Properties();
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", smtp);
		Session session = Session.getInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(_smtpName, _smtpPassword);
			}
		});
		session.setDebug(false);

		MimeMessage msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(MimeUtility.encodeText(sendFrom)));
		msg.setRecipients(RecipientType.TO, InternetAddress.parse(sendTo));
		msg.setSubject(subject);

		// 设置发送时间
		msg.setSentDate(new Date());

		MimeMultipart msgMultipart = new MimeMultipart("mixed");
		msg.setContent(msgMultipart);
		// 发送content
		MimeBodyPart contents = new MimeBodyPart();
		msgMultipart.addBodyPart(contents);

		MimeMultipart bodyMultipart = new MimeMultipart("related");
		contents.setContent(bodyMultipart);
		MimeBodyPart htmlPart = new MimeBodyPart();
		bodyMultipart.addBodyPart(htmlPart);

		htmlPart.setContent(content, "text/html;charset=gbk");
		// 发送附件
		MimeBodyPart attch1 = new MimeBodyPart();
		msgMultipart.addBodyPart(attch1);
		DataSource ds1 = new FileDataSource(accessoryAddress);
		DataHandler dh1 = new DataHandler(ds1);
		attch1.setDataHandler(dh1);
		attch1.setFileName(MimeUtility.encodeText(accessoryName));

		// msg.setHeader("Date", new Date().toString());
		// msg.saveChanges();
		//
		// OutputStream ips = new FileOutputStream("d:/demo3.eml");
		// msg.writeTo(ips);
		// ips.close();
		//
		// msg = new MimeMessage(session, new FileInputStream("d:/demo3.eml"));

		session.setDebug(false);

		try {
			Transport.send(msg, InternetAddress.parse(sendTo));
			return true;
		} catch (Exception e) {
			log.error("mail sender error To: " + sendTo + " Mail Title: " + subject , e);  
			return false;
		}
	}
	
	
	
	   public  void sendMailByAsynchronous(final ISendEmailLogService sendEmailLogService,final SendEmailLog sendEmailLog,final String smtp,final String sendFrom,final String sendTo, final String smtpName, final String smtpPassword, final String content,final String subject) {  
	  
	        new Thread(new Runnable() {  
	            public void run() {  
	                try {  
	                	new SendMail().sendMail(smtp,sendFrom,sendTo,smtpName,smtpPassword,content,subject);
	                	sendEmailLogService.saveSendEmailLog(sendEmailLog);
	                } catch (Exception ex) {  
	                	log.error("mail sender error To: " + sendTo + " Mail Title: " + subject , ex);  
	                }  
	            }  
	        }).start();  
	    }
	
	
	
	
}
